<template>
  <div>
    <Form ref="formData" :model="formData" :label-width="140">
      <Card
        title="维护基本信息"
        :bordered="false"
        dis-hover
        class="ivu-mt i-table-no-border"
      >
        <Row class="card-title" justify="end" type="flex">
          <Col span="4" style="margin: 10px">
            <Button type="primary" :loading="aloading" @click="saveBasicInfo"
              >保存</Button
            >
            <!-- <a @click.prevent="saveBasicInfo" style="margin-left: 20px;">保存</a> -->
            <!-- <a @click.prevent="submitBt" style="margin-right: 20px;margin-left: 20px;" v-show="isSave">提交</a> -->
          </Col>
        </Row>
        <Row class="format_table_wrap">
          <Table
            :columns="columns1"
            :data="baseTableData"
            width="100%"
            ref="table"
          />
        </Row>
      </Card>
    </Form>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';

export default {
  mixins: [],
  components: {},
  data () {
    return {
      totalNum: 0,
      pageShow: 10,
      nowPage: 1,
      aloading: false,
      productType: '02', // 商品类型：01-b2c实物商品;02-o2o实物商品;03-到店服务(预定)商品;04-到店服务（券）;05-上门服务商品;06-活动商品;
      isViewPage: true, // 是否商品详情页
      isSelfShop: false,
      linkAttributeModel: false,
      linshiBaseTableData: [], // 列表的数据源
      baseTableData: [], // 列表的数据源
      state: [],
      name: '',
      isSave: false,
      ready: true, // 用来标识是否准备好,准备好了,就可以提交
      isShowResults: false,
      searchData: [],
      linkAttributeData: [], // 模板数据
      productUuid: '',
      linkAttributeDataCol: [
        {
          title: '模板名称',
          key: 'name'
        },
        {
          title: '模板描述',
          key: 'note'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ],
      selectFieldColu: [
        {
          title: '字段名称',
          key: 'name',
          width: 120,
          align: 'center'
        },
        {
          title: '是否选择',
          slot: 'isSelect',
          width: 120,
          align: 'center'
        }
      ],
      relatedColu: [
        {
          title: '商品名称',
          key: 'productName',
          width: 120
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          width: 120
        },
        {
          title: '商品分类',
          key: 'categoryPath',
          width: 120
        },
        {
          title: '管理区域',
          key: 'manageArea',
          width: 120
        },
        {
          title: '规格参数',
          key: 'saleAttrInfo',
          width: 150
        },
        {
          title: '品牌',
          key: 'brandName',
          width: 150
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 100
        }
      ],
      columns1: [
        {
          title: '品类',
          key: 'categoryPath',
          width: 180
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          width: 180
        },
        {
          title: '商品名称',
          key: 'productNameFinal',
          width: 180
        },
        {
          title: '品牌',
          key: 'brandName',
          width: 150
        }
      ],
      mySubmitList: {},
      specUuid: '', // 选择供应商的规格的skuUuid
      selectSupplyData: [], // 已经选择的供应商数据
      isviewPageNew: false, // 是否是选择规格的查看选择供应商
      templateNameData: [], // 模糊搜索存放数据
      templateNamesData: [], // 模糊搜索存放数据
      recordNo: '', // 单据编号
      operName: '', // 提交人
      opeTime: '', // 提交时间
      operDeptName: '', // 提交部门
      operAreaName: '', // 区域
      formData: {
        categoryName: '',
        templateName: '',
        templateUuid: '',
        spuNo: '',
        productName: ''
      },
      apiObj: {
        // 模板放大镜，弹出模板列表
        getPagerByTemplate: {
          url: '/sysback/batch/prepare/basicinfo/getPagerByTemplate', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 模板-模糊联想精准搜索
        getByTemplateName: {
          url: '/sysback/batch/prepare/basicinfo/getByTemplateName', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 查询基本信息
        queryBasicInfo: {
          url: '/sysback/prepare/commit/basicinfo/queryBasicInfo', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 保存
        saveBasicInfo: {
          url: '/sysback/prepare/commit/basicinfo/saveBasicInfo', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 提交
        commitBasicInfo: {
          url: '/sysback/prepare/commit/basicinfo/commitBasicInfo', // 接口地址
          type: 'post' // 接口请求类型
        }
      }
    };
  },
  created () {
    this.productUuid = this.$route.query.productUuid;
    this.initData();
  },
  mounted () {
    // 刷新页面清除选择的供应商缓存
    window.localStorage.removeItem('selectSupplyList');
  },
  methods: {
    initData () {
      let data = {};
      let colums2 = [];
      // 开始请求列表
      ApiRequest(
        this.apiObj.queryBasicInfo.url + '?productUuid=' + this.productUuid,
        this.apiObj.queryBasicInfo.type,
        data,
        false
      ).then((res) => {
        if (res.retStatus === '1') {
          let reData = res.retData;
          this.baseTableData = [];
          this.baseTableData.push({
            productUuid: reData.main.productUuid,
            productNameFinal: reData.main.productNameFinal,
            brandName: reData.main.brandName,
            categoryPath: reData.main.categoryPath,
            spuNo: reData.main.spuNo,
            saleAttrInfo: reData.main.saleAttrInfo,
            manageArea: reData.main.manageArea
            // attrList: reData.attrList,
          });
          let attrListData = [];
          reData.attrList.forEach((element) => {
            if (element.attrType === '04') {
              let uuids = [];
              let names = [];
              if (element.valueUuid !== '' && element.valueUuid !== null) {
                uuids = element.valueUuid.split(','); // 将字符串转数组
              }
              if (element.valueName !== '' && element.valueName !== null) {
                names = element.valueName.split(','); // 将字符串转数组
              }
              attrListData.push({
                attrType: element.attrType,
                attrMust: element.attrMust,
                canEdit: element.canEdit,
                attrName: element.attrName,
                attrUuid: element.attrUuid,
                officialFlag: element.officialFlag,
                valueUuid: uuids,
                valueName: names,
                allValueOptions: element.allValueOptions
              });
            } else {
              attrListData.push({
                attrType: element.attrType,
                attrMust: element.attrMust,
                canEdit: element.canEdit,
                attrName: element.attrName,
                attrUuid: element.attrUuid,
                valueUuid: element.valueUuid,
                valueName: element.valueName,
                officialFlag: element.officialFlag,
                allValueOptions: element.allValueOptions
              });
            }
          });
          this.baseTableData[0].attrList = attrListData;
          if (this.baseTableData.length === 1) {
            this.baseTableData[0].attrList.forEach((element, myIndex) => {
              if (element.attrType === '01') {
                let myValue = '';
                colums2.push({
                  title: element.attrName,
                  renderHeader: (h, params) => {
                    return h('div', [
                      element.attrMust === '1'
                        ? h(
                            'span',
                            {
                              style: { color: '#ed4014' }
                            },
                            '*'
                          )
                        : '',
                      params.column.title
                    ]);
                  },

                  key: element.attrUuid,
                  width: 150,
                  render: (h, params) => {
                    return h('Input', {
                      props: {
                        value: element.valueName
                      },
                      on: {
                        'on-change': (event) => {
                          myValue = event.target.value;
                          this.onChageRow(
                            params.index,
                            myIndex,
                            0,
                            element,
                            myValue
                          );
                        },
                        'on-blur': (event) => {
                          if (myValue !== '') {
                          }
                        }
                      }
                    });
                  }
                });
              } else if (element.attrType === '02') {
                colums2.push({
                  title: element.attrName,
                  renderHeader: (h, params) => {
                    return h('div', [
                      element.attrMust === '1'
                        ? h(
                            'span',
                            {
                              style: { color: '#ed4014' }
                            },
                            '*'
                          )
                        : '',
                      params.column.title
                    ]);
                  },

                  key: element.attrUuid,
                  width: 150,
                  render: (h, params) => {
                    return h(
                      'Select',
                      {
                        props: {
                          value: element.valueName,
                          transfer: true
                        },
                        on: {
                          'on-change': (event) => {
                            this.onChageRow(
                              params.index,
                              myIndex,
                              0,
                              element,
                              event
                            );
                          }
                        }
                      },
                      element.allValueOptions.map((item) => {
                        // this.productTypeList下拉框里的data
                        return h('Option', {
                          // 下拉框的值
                          props: {
                            value: item.optionHtml,
                            label: item.optionHtml
                          }
                        });
                      })
                    );
                  }
                });
              } else if (element.attrType === '03') {
                colums2.push({
                  title: element.attrName,
                  renderHeader: (h, params) => {
                    return h('div', [
                      element.attrMust === '1'
                        ? h(
                            'span',
                            {
                              style: { color: '#ed4014' }
                            },
                            '*'
                          )
                        : '',
                      params.column.title
                    ]);
                  },

                  key: element.attrUuid,
                  width: 150,
                  render: (h, params) => {
                    return h(
                      'RadioGroup',
                      {
                        props: {
                          value: element.valueName
                        },
                        on: {
                          'on-change': (event) => {
                            this.onChageRow(
                              params.index,
                              myIndex,
                              0,
                              element,
                              event
                            );
                          }
                        }
                      },
                      [
                        element.allValueOptions.map((item) => {
                          // this.productTypeList下拉框里的data
                          return h(
                            'Radio',
                            {
                              props: {
                                value: item.optionHtml,
                                label: item.optionHtml
                              },
                              on: {}
                            },
                            params.row.optionValue
                          );
                        })
                      ]
                    );
                  }
                });
              } else {
                colums2.push({
                  title: element.attrName,
                  renderHeader: (h, params) => {
                    return h('div', [
                      element.attrMust === '1'
                        ? h(
                            'span',
                            {
                              style: { color: '#ed4014' }
                            },
                            '*'
                          )
                        : '',
                      params.column.title
                    ]);
                  },

                  key: element.attrUuid,
                  width: 150,
                  render: (h, params) => {
                    return h(
                      'CheckboxGroup',
                      {
                        props: {
                          value: element.valueName
                        }
                      },
                      [
                        element.allValueOptions.map((item, index3) => {
                          // this.productTypeList下拉框里的data
                          return h(
                            'Checkbox',
                            {
                              // 下拉框的值
                              props: {
                                value: item.optionValue,
                                label: item.optionHtml
                              },
                              on: {
                                input: (event) => {
                                  this.onChageRow(
                                    params.index,
                                    myIndex,
                                    index3,
                                    element,
                                    event
                                  );
                                }
                              }
                            },
                            params.row.optionValue
                          );
                        })
                      ]
                    );
                  }
                });
              }
            });
            colums2.forEach((element) => {
              this.columns1.push(element);
            });
          }
        }
      });
    },
    // 保存
    saveBasicInfo () {
      let notSpecList = [];
      this.mySubmitList = {};
      this.ready = true;
      this.baseTableData.forEach((element) => {
        element.attrList.forEach((item) => {
          if (item.attrType === '04') {
            let values = '';
            if (item.valueUuid != '' && item.valueUuid != null) {
              values = item.valueUuid.join(',');
            }
            if (item.attrMust === '1' && values === '') {
              this.ready = false;
              this.$Message.error(item.attrName + '不能为空');
              return false;
            }
            notSpecList.push({
              attrInfo: item.attrUuid || item.attrName,
              officialFlag: item.officialFlag,
              valueInfo: values
            });
          } else if (item.attrType === '02' || item.attrType === '03') {
            let values = '';
            item.allValueOptions.forEach((a) => {
              if (a.optionHtml === item.valueName) {
                values += a.optionValue;
              }
            });
            if (item.attrMust === '1' && values === '') {
              this.ready = false;
              this.$Message.error(item.attrName + '不能为空');
              return false;
            }
            notSpecList.push({
              attrInfo: item.attrUuid || item.attrName,
              officialFlag: item.officialFlag,
              valueInfo: values
            });
          } else {
            if (item.attrMust === '1' && item.valueName === '') {
              this.ready = false;
              this.$Message.error(item.attrName + '不能为空');
              return false;
            }
            notSpecList.push({
              attrInfo: item.attrUuid || item.attrName,
              officialFlag: item.officialFlag,
              valueInfo: item.valueName
            });
          }
        });
      });
      if (!this.ready) {
        this.$Message.error('确保列表内容不能为空');
        return false;
      }
      this.mySubmitList.productUuid = this.productUuid;
      this.mySubmitList.notSpecList = notSpecList;
      this.aloading = true;
      ApiRequest(
        this.apiObj.saveBasicInfo.url,
        this.apiObj.saveBasicInfo.type,
        this.mySubmitList,
        false
      )
        .then((res) => {
          if (res.retStatus === '1') {
            this.$Message.success('保存成功');
            this.isSave = true;
          }
          this.aloading = false;
        })
        .catch(() => {
          this.aloading = false;
        });
    },
    // 提交
    submitBt () {
      ApiRequest(
        this.apiObj.commitBasicInfo.url + '?productUuid=' + this.productUuid,
        this.apiObj.commitBasicInfo.type,
        this.mySubmitList,
        false
      ).then((res) => {
        if (res.retStatus === '1') {
          this.$Message.success('提交成功');
          this.mySubmitList = [];
          this.baseTableData = [];
        }
      });
    },
    // 数据赋值处理
    onChageRow (index, index2, index3, attr, value) {
      // 判断是否包含税类,如果包含税类,就关联税类代码和税率
      if (attr.attrType === '04') {
        let data = this.baseTableData[index].attrList[index2];
        if (value) {
          data.valueName.push(data.allValueOptions[index3].optionHtml);
          data.valueUuid.push(data.allValueOptions[index3].optionValue);
        } else {
          data.valueName.forEach((element, i) => {
            if (data.allValueOptions[index3].optionHtml === element) {
              data.valueName.splice(i, 1);
              data.valueUuid.splice(i, 1);
            }
          });
        }
      } else {
        this.baseTableData[index].attrList[index2].valueName = value;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.div {
  display: flex;

  > span:nth-of-type(2),
  > span:nth-of-type(3) {
    margin-left: 20px;
  }
}

.a {
  background: #5d8ae3 !important;

  > div {
    border-left: 40px solid #5d8ae3 !important;
  }
}

.b {
  background: #5d8ae3 !important;

  > div:nth-of-type(1) {
    border-left: 40px solid #5d8ae3 !important;
  }

  > div:nth-of-type(2) {
    position: absolute;
    top: 0px;
    left: -20px;
    border-top: 20px solid #5d8ae3 !important;
    border-right: 0px solid #5d8ae3 !important;
    border-bottom: 20px solid #5d8ae3 !important;
  }
}

.btn {
  width: 120px;
  margin: 16px 20px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  color: white;
  font-size: 15px;
  border-radius: 4px;
  background: #5d8ae3;
}

.search {
  width: 100%;
  padding: 10px 64px;
  background: #eaf7f9;
}
</style>
